﻿using EMS.system.Entityies.BaseData;
using EMS.system.IEntityAppService.BaseData.IRoleService;
using EMS.system.IEntityAppService.BaseData.IRoleService.RoleDto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace EMS.system.EntityAppService.BaseData
{
    public class RoleAppService:ApplicationService, IRoleAppService
    {
        private readonly IRepository<Role> _repository;

        public RoleAppService(IRepository<Role> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 角色新增
        /// </summary>
        /// <param name="addDto"></param>
        /// <returns></returns>
        public async Task<int> RoleAdd(RoleAddDto addDto)
        {
            Role role = await _repository.InsertAsync(ObjectMapper.Map<RoleAddDto, Role>(addDto));
            return role == null ? 0 : 1;
        }

        /// <summary>
        /// 显示角色
        /// </summary>
        /// <param name="name"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<PagedResult> RoleList(string? name, int page, int limit)
        {
            PagedResult result = new PagedResult();
            List<Role> roles = await _repository.GetListAsync(x => (string.IsNullOrEmpty(name) || x.RoleName.Contains(name)));
            result.CurrentPage = page;
            result.PageSize = limit;
            result.RowCount = roles.Count;
            result.PageCount = (int)Math.Ceiling(roles.Count * 1.0 / limit);
            result.Queryable = roles.Skip((page - 1) * limit).Take(limit).AsQueryable();
            return result;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> RoleDel(string ids)
        {
            await _repository.DeleteAsync(x => ids.Contains(x.Id.ToString()));
            return 1;
        }

        /// <summary>
        /// 获取单个角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RoleUpdDto> GetSingRole(int id)
        {
            Role role = await _repository.FirstOrDefaultAsync(x => x.Id == id);
            return ObjectMapper.Map<Role, RoleUpdDto>(role);
        }

        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<int> RoleUpd(RoleUpdDto dto)
        {
            Role role = ObjectMapper.Map<RoleUpdDto, Role>(dto);
            Role roleup = await _repository.UpdateAsync(role);
            return roleup == null ? 0 : 1;
        }
    }
}
